package com.yoooya.base.admin.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.MessageSource;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.yoooya.base.admin.interceptor.SessionContext;
import com.yoooya.base.model.vo.LoginUser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @创建人 Sun Yijing
 * @创建时间 2018-06-28
 */
public abstract class AbstractController {

	protected static final String VIEW_NOT_EXISTS = "none";

	@Autowired
	protected MessageSource messageSource;

	@Autowired
	protected HttpServletRequest request;
	@Autowired
	protected HttpServletResponse response;

	private String viewPath = "";

	private String moduleName = "";

	private String resourcePath = "/resources";

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		CustomDateEditor dateEditor = new CustomDateEditor(fmt, true);
		binder.registerCustomEditor(Date.class, dateEditor);
		binder.setValidator(this.getValidator());
	}

	/**
	 * @return
	 */
	protected Validator getValidator() {
		return null;
	}

	/**
	 * 默认执行方法，请求必需以.html结尾
	 */
	@RequestMapping(value = "/**/*.html", method = RequestMethod.GET)
	public ModelAndView defaultHandler() {
		String requestURI = this.getRequest().getRequestURI();
		requestURI = requestURI.replace(this.getRequest().getContextPath(), "");
		RequestMapping requestMapping = this.getClass().getAnnotation(
				RequestMapping.class);
		if (requestMapping != null && requestMapping.value().length > 0) {
			requestURI = requestURI.replaceAll(requestMapping.value()[0], "");
		}
		if (requestURI.indexOf(".") != -1) {
			requestURI = requestURI.substring(0, requestURI.indexOf("."));
		}
		ModelAndView view = new ModelAndView(requestURI);
		return this.correctView(view);
	}

	public void correctTheme(Map<String, String> themeMap) {
		if (!(themeMap == null || StringUtils.isBlank(themeMap.get("viewPath")) || StringUtils
				.isBlank(themeMap.get("resourcePath")))) {
			this.viewPath = themeMap.get("viewPath");
			this.resourcePath = themeMap.get("resourcePath");
		}
		request.setAttribute("contextPath", request.getContextPath());
		request.setAttribute("resourcePath", request.getContextPath()
				+ this.resourcePath);

	}

	/**
	 * 获取路径
	 * 
	 * @return
	 */
	public String getContextPath() {
		String contextPath = request.getContextPath();
		String requestURL = request.getRequestURL().toString();
		String requestURI = request.getRequestURI();
		if (!requestURI.equals("/")) {
			requestURL = requestURL.replace(requestURI, "");
		}
		if (requestURL.endsWith("/")) {
			requestURL = requestURL.substring(0, requestURL.length() - 1);
		}

		if (contextPath.equals("/")) {
			contextPath = "";
		}
		return requestURL + contextPath;
	}

	/**
	 * 修正前台的路径
	 * 
	 * @param view
	 * @return
	 */
	public ModelAndView correctView(ModelAndView view) {
		if (view == null) {
			view = new ModelAndView(VIEW_NOT_EXISTS);
		}
		if (StringUtils.isEmpty(view.getViewName())) {
			view.setViewName(VIEW_NOT_EXISTS);
		}
		String viewName = view.getViewName();
		viewName = this.correctViewName(viewName);
		view.setViewName(viewName);
		view.addObject("requestURI", this.request.getRequestURI());
		if (!StringUtils.isEmpty(moduleName)) {
			view.addObject("moduleName", moduleName);
		}
		return view;
	}

	/**
	 * 修正前台的视图名称
	 * 
	 * @param viewName
	 * @return
	 */
	public String correctViewName(String viewName) {
		if (StringUtils.isBlank(viewName)) {
			return viewName;
		}

		String selfBasePath = this.getSelfBasePath();
		if (StringUtils.isBlank(selfBasePath)) {
			selfBasePath = "";
		} else {
			if (!selfBasePath.startsWith("/")) {
				selfBasePath = "/" + selfBasePath;
			}
		}

		if (!viewName.startsWith("/")) {
			viewName = "/" + viewName;
		}
		String fixedViewName = viewPath + selfBasePath + viewName;
		fixedViewName = fixedViewName.replaceAll("//", "/").replaceAll(" ", "");
		return fixedViewName;
	}

	public abstract String getSelfBasePath();

	/**
	 * @return the request
	 */
	public HttpServletRequest getRequest() {
		return this.request;
	}

	/**
	 * 获得完整访问路径的前缀
	 * 
	 * @return
	 */
	public String getRequestUrlPrefix() {
		String requestURL = this.getRequest().getRequestURL().toString();
		String requestURI = this.getRequest().getRequestURI();
		requestURL = requestURL.replace(requestURI, "");
		String contextPath = this.getRequest().getContextPath();
		return requestURL + contextPath;
	}

	protected String getFromUrl() {
		String fromUrl = this.getRequest().getHeader("referer");
		if (fromUrl == null) {
			fromUrl = this.getRequest().getRequestURL().toString();
		} else {
			if (fromUrl.equals(this.getRequest().getRequestURL().toString())) {
				return (String) this.getRequest().getSession()
						.getAttribute("fromUrl");
			}
		}
		this.getRequest().getSession().setAttribute("fromUrl", fromUrl);
		return fromUrl;
	}

	public String getModuleName() {
		return moduleName;
	}

	public void setModuleName(String moduleName) {
		this.moduleName = moduleName;
	}

	public SessionContext getSessionContext() {
		return SessionContext.getSessionContext(this.getRequest());
	}

	/*
	 * 获得当前登入用户
	 */
	public Long getUserId() {
		return this.getSessionContext().getUserId();
	}

	/**
	 * 获取登录用户
	 * 
	 * @return
	 */
	public LoginUser getUser() {
		return this.getSessionContext().getUser();
	}

	public Boolean isUserLoginFlag() {
		return this.getSessionContext().isUserLoginFlag();
	}

}
